package cn.smbms.controller;

import cn.smbms.pojo.User;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    UserService userService;

    private Logger logger = Logger.getLogger(LoginController.class);

    @RequestMapping(value="/login.html")
    public String login(){
        logger.debug("LoginController welcome SMBMS==================");
        return "login";
    }

    @RequestMapping(value="/sys/main.html")
    public String main(){
        return "frame";
    }

    @RequestMapping(value="/dologin.html",method=RequestMethod.POST)
    public String doLogin(@RequestParam String userCode, @RequestParam String userPassword, HttpSession session, HttpServletRequest request) throws Exception{
        logger.debug("doLogin====================================");
        //调用service方法，进行用户匹配
        User user = userService.login(userCode,userPassword);

        if(null != user){//登录成功
            session.setAttribute(Constants.USER_SESSION, user);
            //页面跳转（frame.jsp）
            return "redirect:/sys/main.html";
        }else{
            request.setAttribute("error","用户名或密码不正确");
            //页面跳转（login.jsp）
            return "login";
        }
    }

    @RequestMapping(value="/main.html")
    public String main(HttpSession session){
        if(session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/user/login.html";
        }
        return "frame";
    }



}
